<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 TRANSITIONAL//EN">
<html>
	<head>
		<meta content="yes" name="apple-mobile-web-app-capable" />
		<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type" />
		<meta content="minimum-scale=1.0, width=device-width, maximum-scale=0.6667, user-scalable=no" name="viewport" />
		<link href="/static/css/style.css" rel="stylesheet" type="text/css" />
		<link href="/static/css/astar_style.css" rel="stylesheet" type="text/css" />
		<link rel="stylesheet" href="/static/css/jNotify.jquery.css" type="text/css" />
		<script src="/static/js/functions.js" type="text/javascript"></script>
		<script type="text/javascript" src="/_ah/channel/jsapi"></script>
		<script type='text/javascript' src='/static/js/jquery.min.js'></script>
		<script type='text/javascript' src='/static/js/jquery-tmpl.min.js'></script>
		<script type='text/javascript' src='/static/js/knockout-2.1.1.js'></script>
		<script type='text/javascript' src='/static/js/jquery.quicksand.js'></script>
		<script type="text/javascript" src="/static/js/jNotify.jquery.js"></script>
		<link rel="apple-touch-icon" href="homescreen.png"/>
		<link href="startup.png" rel="apple-touch-startup-image" />	
		<title>Audience Star: {{talk.title}}</title>

	<!--Pre-define the view model so we don't get javascript data-bind errors-->
	<script type="text/javascript">
	var view_model = {prevTopic:function(){}, nextTopic:function(){}, startDemographics:function() {},
					  startRanking:function(){}, startTalk:function(){}, endTalk:function(){},
					  numCat1:ko.observable(0), numCat2:ko.observable(0), numCat3:ko.observable(0)};
	</script>
	</head>

<body>

	<div id="topbar">
		<div id="leftnav"><a data-bind="click:view_model.prevTopic" href="#"><span id="leftnav_text">Prev. Topic</span></a></div>
			<div id="title">www.audiencestar.com/go/{{talk.short_title}}</div>
		<div id="rightnav"><a data-bind="click:view_model.nextTopic" href="#"><span id="rightnav_text">Next Topic</span></a></div>
	</div>
	<div id="content">
		<div id="tributton">
			<div class="links"><a data-bind="click:view_model.startDemographics" href="#">Get Demographics</a><a data-bind="click:view_model.startRanking" href="#">Get Topic Rankings</a><a data-bind="click:view_model.startTalk" href="#">Get Started!</a></div></div>
			
		<div id="rightbutton"><a data-bind="click:view_model.endTalk" href="#">End Presentation</a></div>
	
<!--<b>Session ID:</b>{{session_id}}<br/>-->
<div id="NOT_STARTED" style="display:block">
			<ul class="pageitem">
				<li class="textbox"><span class="header">www.audiencestar.com/go/{{talk.short_title}}</span><p>
				Visit the above URL on your mobile phone, tablet or laptop to participate in this presentation.</p>
				</li>
			</ul>
			
			<ul class="pageitem">
				<li class="textbox"><span class="header">Audience Demographics:</span>
				<b>{{talk.category1}}:</b> <span id="num_category1" ></span><br/>
				<b>{{talk.category2}}:</b> <span id="num_category2" ></span><br/>
				<b>{{talk.category3}}:</b> <span id="num_category3" ></span><br/>
				
				</li>
			
			</ul>
</div>
<!-- END NOT_STARTED DIV -->


<!-- RANKING TOPICS DIV -->
<div id="RANKING" style="display:block; height=2000px">
		<ul id="topics">
		{% for topic in topics %}
			<li id="topic-{{topic.key.id}}" class="sortable" data-id="topic-{{topic.key.id}}" data-type="sortable_topic">
				<ul class="pageitem">
					<li class="textbox"><span class="header">{{topic.title}} (<span data-type="ranking" id="avg_ranking_topic-{{topic.key.id}}">0</span>)</span>{{topic.description}}</li>
				</ul>
			</li>
		{% endfor %}
		</ul>
</div>
<!-- END RANKING TOPICS DIV -->

<!-- STARTED DIV -->
<div id="STARTED" style="display:block">	
		<div id="content">
		
			<ul class="pageitem">
				<li class="textbox"><span class="header"><span data-bind="text:view_model.currentTopicTitle" id="current_topic_title"></span></span>
				<span data-bind="text:view_model.currentTopicDescription" id="current_topic_description"></span>
				</li>
			</ul>
			<span class="graytitle">Questions:</span>
			<ul class="pageitem">
						<div data-bind="template: {name:'questionTemplate', foreach: questionModel.questions}"></div>

					<script type="text/x-jquery-tmpl" id="questionTemplate">
						<li class="textbox">
							<span class="header" data-bind="text: asker_name"/> 
							<span data-bind="text: question_text"/><br/>
							<hidden data-bind="value: key"/><a href="#" data-bind="click: remove">Clear</a>
						</li>
					</script>
				</li>
			</ul>
	</div>
</div>
<!-- END OF STARTED DIV -->

<div id="footer">
	<a href="http://www.pargman.com">AudienceStar by Randy Pargman</a> (<span id="connected_state">DISCONNECTED</span>)
</div>


<!--
{'key':topic.key(), 
 'data_id':'topic-'+str(topic.key().id()), 
 'num_very_interested':topic.num_very_interested, 
 'avg_ranking':math.round(50*topic.avg_ranking + 50),
 'sort_index':sort_index}
-->

<!-- Script to take a list of topic data and update all the topics on screen -->
<script type="text/javascript">
var current_view = "{{talk.state}}";
var updating_ranks = false;
function updateTopicRankings(rankings_list) {
	if (current_view != "RANKING") return; // Don't update rankings if we aren't in that mode
	updating_ranks = true; // Don't allow updates while we're in the middle of this
	// get the topics list
	var $data = $('#topics');
	var $filteredData = $data.find('li[data-type=sortable_topic]');
	// clone topics to get a second collection
	var $cloned_topics = $filteredData.clone();
	
	// Update the elements of the cloned list
	for (var i=0; i<rankings_list.length; i++) {
		var topic_ranking = rankings_list[i];
		var topic_id = topic_ranking.data_id;
		var topic_selector = '#'+topic_id;
		var avg_ranking_selector = "#avg_ranking_"+topic_id;
		var avg_ranking_element = $cloned_topics.find(avg_ranking_selector);
		avg_ranking_element.html(topic_ranking.avg_ranking);
	}
	  
	 
	 var $sortedData = $cloned_topics.sorted({
        by: function(v) {
          return parseFloat($(v).find('span[data-type=ranking]').text());
        }
     });
     
	
	 // finally, call quicksand
    $data.quicksand($sortedData, {
      duration: 600
    });
	updating_ranks = false; // allow more updates
}

function getTopicRanks() {
	if (current_view == "RANKING") {
		$.get("/ranktopic/getrankings", {talk_key: "{{talk.key}}"}, 
			function(data) {
				var messageObject = eval('(' + data + ')');
				if (messageObject.message == "rankings_changed" && messageObject.topics_list) {
					updateTopicRankings(messageObject.topics_list);            
    			}
    			else {
    				jError("Topic ranking list format is not valid");
    			}
			}
		);
	}
}

function getDemographics() {
	if (current_view == "NOT_STARTED") {
		//only update demographics if we're in the NOT_STARTED state
		$.get("/star/getdemographics", {talk_key: "{{talk.key}}"},
			function(data) {
				var messageObject = eval('(' + data + ')');
				if (messageObject.message == "demographics") {
					//jNotify("updating demographics");
					$("#num_category1").html(messageObject.num_category1);
					$("#num_category2").html(messageObject.num_category2);
					$("#num_category3").html(messageObject.num_category3);
					//view_model.numMales(messageObject.num_males);
					//view_model.numFemales(messageObject.num_females);
					//view_model.numCat1(messageObject.num_category1);
					//view_model.numCat2(messageObject.num_category2);
					//view_model.numCat3(messageObject.num_category3);
    			}
    			else {
    				jError("demographic data format is not valid");
    			}	
			}
		);	
		
	}	
}

setInterval("getTopicRanks()", 5000); // update ranks every 5 sec
setInterval("getDemographics()", 4500); // update demographics every 4.5 sec
</script>

<!-- Script to show the correct view -->
<script type="text/javascript">
var not_started = document.getElementById("NOT_STARTED");
var ranking = document.getElementById("RANKING");
var started = document.getElementById("STARTED");
var finished = document.getElementById("FINISHED");
var view_list = [not_started, ranking, started, finished];
//alert(view_list);
function showCurrentView(view_to_show) {
	for (var i=0; i<view_list.length; i++) {
		var view_element = view_list[i];
		if (view_element)
			view_element.style.display="none";
	}
	var view_to_show_div = document.getElementById(view_to_show);
	//alert(view_to_show);
	if (view_to_show_div) {
		view_to_show_div.style.display = "block";
		view_to_show_div.style.height = "100%";
		current_view = view_to_show;
	} else {
		alert("invalid display state: " + view_to_show);
	}
}
showCurrentView("{{talk.state}}");
</script>

<!-- QUESTIONS MODEL -->
<script type="text/javascript">
// Class to represent a row in the question grid
var Question = function(key, asker_name, question_text) {
	this.key = ko.observable(key);
    this.asker_name = ko.observable(asker_name);
    this.question_text = ko.observable(question_text);
    
    this.remove = function() {
		questionModel.questions.remove(this);
		var question_key = this.key;
		$.post("/question/answered", {question_key:question_key});
	};
}

var questionModel = {
	questions: ko.observableArray([
	{% for question in unanswered_questions %}
		new Question("{{question.key}}", "{{question.star.display_name}}", "{{question.text}}"), 
    {% endfor %}
    ])
};



ko.applyBindings(questionModel);
</script>




<!-- View Model -->

<script type="text/javascript">
var view_model = {
    numFemale: ko.observable(0),
    numMale: ko.observable(0),
    numCat1: ko.observable(0),
    numCat2: ko.observable(0),
    numCat3: ko.observable(0),
    avgAge: ko.observable(0),
	currentTopicTitle: ko.observable("Topic Title"),
	currentTopicDescription: ko.observable("Topic description goes here."),
	
	startDemographics: function() {
		$.get("/admin/talk/change_state/{{talk.short_title}}", { new_state: "NOT_STARTED" },
			function(data) {
				//alert("Data Loaded: " + data);
		});
		showCurrentView("NOT_STARTED");
		$("#leftnav").hide(); // don't show the left nav button when we're in demographic mode
		$("#rightnav").show(); // make sure we can see the right nav button
		$("#rightnav_text").html("Rank Topics"); // set the text of the right nav button to what it does
	},
	
	startRanking: function() {
		$.get("/admin/talk/change_state/{{talk.short_title}}", { new_state: "RANKING" },
			function(data) {
				//alert("Data Loaded: " + data);
		});
		showCurrentView("RANKING");
		$("#leftnav").show(); // show the left nav button
		$("#leftnav_text").html("Demographics");
		$("#rightnav").show(); // make sure we can see the right nav button
		$("#rightnav_text").html("Start"); // set the text of the right nav button to what it does
	},
	
	startTalk: function() {
		showCurrentView("STARTED"); // hide/unhide the correct DOM elements to show the talk started screen
		var viewModel = this;
		$.get("/admin/talk/change_state/{{talk.short_title}}", { new_state: "STARTED" },
			function(data) {
				var messageObject = eval('(' + data + ')'); 
				if (messageObject.current_topic_title) {
					//alert(messageObject.current_topic_title);
					view_model.currentTopicTitle(messageObject.current_topic_title);
					view_model.currentTopicDescription(messageObject.current_topic_description);
				}
			}
		);
		$("#leftnav").show(); // show the left nav button
		$("#leftnav_text").html("Prev. Topic");
		$("#rightnav").show(); // make sure we can see the right nav button
		$("#rightnav_text").html("Next Topic"); // set the text of the right nav button to what it does
	},
	
	endTalk: function() {
		$.get("/admin/talk/change_state/{{talk.short_title}}", {new_state: "FINISHED"});
		window.location = "/final/{{talk.short_title}}";	
	},
	
	changeTopic: function(next_or_prev) {
		var viewModel = this;
		$.get('/admin/talk/change_topic/{{talk.short_title}}', { direction: next_or_prev}, 
			function(data) {
				//alert(data);
				var messageObject = eval('(' + data + ')'); // parse the json object
				if (messageObject.current_topic_title) {
					view_model.currentTopicTitle(messageObject.current_topic_title);
					view_model.currentTopicDescription(messageObject.current_topic_description);
				}			
			}
		);
	},
	
	prevTopic: function() {
		if (current_view=="STARTED") {
			view_model.changeTopic('prev');
		} else if (current_view == "RANKING") {
			view_model.startDemographics();
		}
	},
	
	nextTopic: function() {
		if (current_view=="STARTED") {
			view_model.changeTopic('next');
		} else if (current_view == "NOT_STARTED") {
			view_model.startRanking();
		} else if (current_view == "RANKING") {
			view_model.startTalk();	
		}
	},
};

//var view_model = new demographicViewModel();

ko.applyBindings(view_model);

</script>



<script type="text/javascript">

onOpened = function() {
  connected = true;
  $("#connected_state").html("CONNECTED");
  jNotify("channel opened");
};

onMessage = function(message) {
	//jNotify("Message received:"+message.data);
	var messageObject = eval('(' + message.data + ')');
	
    if (messageObject.new_question) {
    	questionModel.questions.push(new Question(messageObject.new_question.key,
    											  messageObject.new_question.asker_name,
    											  messageObject.new_question.question_text));	
    }
    
};

onError = function(message) {
	jError("Channel error: "+message.description);
};

onClose = function() {
	//alert("channel closed");
	connected = false;
	$("#connected_state").html("DISCONNECTED");
	jError("Channel Closed");
};

    channel = new goog.appengine.Channel('{{ token }}');
    socket = channel.open();
    socket.onopen = onOpened;
    socket.onmessage = onMessage;
    socket.onerror = onError;
    socket.onclose = onClose;
</script>

<script type="text/javascript">
// Custom sorting plugin
(function($) {
  $.fn.sorted = function(customOptions) {
    var options = {
      reversed: true,
      by: function(a) { return a.text(); }
    };
    $.extend(options, customOptions);
    $data = $(this);
    arr = $data.get();
    arr.sort(function(a, b) {
      var valA = options.by($(a));
      var valB = options.by($(b));
      if (options.reversed) {
        return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
      } else {		
        return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
      }
    });
    return $(arr);
  };
})(jQuery);

// DOMContentLoaded
$(function() {
	//$('#leftnav').hide();
	//$('#rightnav"').hide();
	$.get( '/get/rankings/{{talk.short_title}}', function(data) {
		//alert("Getting first rankings from server: "+ data);
		var messageObject = eval('(' + data + ')');
		if (messageObject.message == "rankings_changed") {
			updateTopicRankings(messageObject.topics_list); 
		}			
    });

});
</script>
</body>
</html>